import { createRouter, createWebHistory } from 'vue-router'
import { message } from 'ant-design-vue'
import Home from '@/views/Home.vue'
import Wardrobe from '@/views/Wardrobe.vue'
import Fitting from '@/views/Fitting.vue'
import Login from '@/views/Login.vue'
import Register from '@/views/Register.vue'
import Profile from '@/views/Profile.vue'
import AIAssistant from '@/views/AIAssistant.vue'

const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home,
    meta: { requiresAuth: true }
  },
  {
    path: '/login',
    name: 'Login',
    component: Login,
    meta: { requiresAuth: false }
  },
  {
    path: '/register',
    name: 'Register',
    component: Register,
    meta: { requiresAuth: false }
  },
  {
    path: '/fitting',
    name: 'Fitting',
    component: Fitting,
    meta: { requiresAuth: true }
  },
  {
    path: '/wardrobe',
    name: 'Wardrobe',
    component: Wardrobe,
    meta: { requiresAuth: true }
  },
  {
    path: '/recommend',
    name: 'Recommend',
    component: () => import('@/views/Recommend.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/ai-assistant',
    name: 'AIAssistant',
    component: AIAssistant,
    meta: { requiresAuth: true }
  },
  {
    path: '/profile',
    name: 'Profile',
    component: Profile,
    meta: { requiresAuth: true }
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  console.log('Route guard triggered:')
  console.log('To:', to.path)
  console.log('Requires auth:', to.meta.requiresAuth)

  const token = localStorage.getItem('token')
  const userId = localStorage.getItem('userId')

  console.log('Auth check:')
  console.log('Token exists:', !!token)
  console.log('User ID exists:', !!userId)

  if (to.meta.requiresAuth) {
    if (!token || !userId) {
      console.log('Auth failed - redirecting to login')
      message.error('请先登录')
      next('/login')
    } else {
      console.log('Auth successful')
      next()
    }
  } else {
    next()
  }
})

export default router 